package com.leenmvc.core.security.service.core;

import com.leenmvc.core.annotation.TransactionMulti;
import com.leenmvc.core.base.BaseService;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.security.dao.core.SysRoleMenuDao;
import com.leenmvc.core.security.entity.core.SysRoleMenu;
import com.leenmvc.core.utils.TipUtil;
import com.leenmvc.core.utils.unique.SnowFlake;
import com.leenmvc.core.utils.validator.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: JohnCoding
 * @Description:
 * @date: 2019/12/13 10:46
 */
@Service
public class SysRoleMenuService extends BaseService<SysRoleMenu> {

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    @TransactionMulti
    @Override
    public <T> boolean insert(T t) {
        SysRoleMenu sysRoleMenu = (SysRoleMenu) t;
        ValidatorUtils.notNull(TipUtil.getTip("NOTNULL_FAIL"), sysRoleMenu);
        Long[] menuList = sysRoleMenu.getMenuList();
        if (menuList != null) { // 通过menulist添加
            int length = menuList.length;
            for (int i = 0; i < length; i++) {
                sysRoleMenu.setId(SnowFlake.generateId());
                sysRoleMenu.setMenuId(menuList[i]);
                if (!sysRoleMenuDao.insert(sysRoleMenu)) {
                    return false;
                }
            }
        } else if (sysRoleMenu.getMenuId() != null) {// 通过menuId添加
            if(!sysRoleMenuDao.insert(sysRoleMenu)) {
                return false;
            };
        } else {
            return false;
        }
        return true;
    }

    @Override
    @TransactionMulti
    public <T> boolean update(T t) {
        SysRoleMenu srm = (SysRoleMenu) t;
        if (srm.getMenuList()!=null){
            if (srm.getMenuList().length>1){
                throw new BusinessException("不能够同时修改两项，请检查！");
            }
            srm.setMenuId(srm.getMenuList()[0]);
            if (!sysRoleMenuDao.update(srm)) {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    @Override
    public <T> T get(Object id) {
        SysRoleMenu sysRoleMenu = sysRoleMenuDao.get(id);
        if (sysRoleMenu == null) {
            throw new BusinessException("NOTNULL_FAIL");
        }
        Long menuId = sysRoleMenu.getMenuId();
        Long[] menuList = sysRoleMenu.getMenuList();
        menuList = new Long[]{menuId};
        sysRoleMenu.setMenuList(menuList);
        sysRoleMenu.setMenuId(null);
        return (T) sysRoleMenu;
    }
}
